package three_xia.virPlace;

import java.util.concurrent.TimeUnit;

public class RequestController {
    private static final long DUPLICATE_REQUEST_TTL = 10; // 过期时间（秒）


    private final StringRedisTemplate redisTemplate;


    public RequestController(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    //判断是否重复请求
    private boolean isDuplicateRequest(String requestId, String userId) {
        String redisKey = "request:" + userId + ":" + requestId;
        Boolean exists = redisTemplate.hasKey(redisKey);
        if (Boolean.TRUE.equals(exists)) {
            return true;
        }
        redisTemplate.set(redisKey, "1", DUPLICATE_REQUEST_TTL, TimeUnit.SECONDS);
        return false;
    }

    //@PostMapping("/process")
    public ResponseEntity processRequest(RequestData requestData) {
        String userId = requestData.getUserId();
        String requestId = requestData.getRequestId();

        if (userId == null || requestId == null) {
            return (ResponseEntity) ResponseEntity.badRequest().body();
        }

        //唯一请求和唯一用户id,没有锁就当即执行
        if (isDuplicateRequest(requestId, userId)) {
            return (ResponseEntity) ResponseEntity.status("HttpStatus.CONFLICT").body();
        }

        // 有锁,等待一会模拟在执行(或者返回信息提醒稍后操作),最后返回成功信息
        try {
            Thread.sleep(2000); // 模拟耗时操作
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return ResponseEntity.ok("Request processed successfully");
    }

}



/*import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class IdempotenceTest {

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Test
    public void interfaceIdempotenceTest() throws Exception {
        // 初始化 MockMvc
        MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        // 调用获取 Token 接口
        String token = mockMvc.perform(MockMvcRequestBuilders.get("/token")
                .accept(MediaType.TEXT_HTML))
                .andReturn()
                .getResponse().getContentAsString();
        log.info("获取的 Token 串：{}", token);
        // 循环调用 5 次进行测试
        for (int i = 1; i <= 5; i++) {
            log.info("第{}次调用测试接口", i);
            // 调用验证接口并打印结果
            String result = mockMvc.perform(MockMvcRequestBuilders.post("/test")
                    .header("token", token)
                    .accept(MediaType.TEXT_HTML))
                    .andReturn().getResponse().getContentAsString();
            log.info(result);
            // 结果断言
            if (i == 0) {
                Assert.assertEquals(result, "正常调用");
            } else {
                Assert.assertEquals(result, "重复调用");
            }
        }
    }

}*/